package soundChaser;

/**
 * This class continuously tests the audio player (= Polling). 
 * If another 100ms have passed, then the DMX signal should change.
 * 
 * @author jm
 * 
 */
public class AudioTime extends Thread
{
	AudioPlayer player;
	AudioAnalyzer audioAna;
	double[][] wavearray;
	long waveBitrate;
	int j = 0;

	public AudioTime(AudioPlayer player, AudioAnalyzer audioAna, double[][]wavearray,long waveBitrate)
	{
		this.player = player;
		this.audioAna = audioAna;
		this.wavearray = wavearray;
		this.waveBitrate = waveBitrate;
	}

	public void getTime()
	{
		double[][] wavearrayn = new double[2][(int) (waveBitrate/10)];
		final int interpolStepSize = 100;
		// a real value for values is not allowed!!!
		int time;
		int tempInterpolSteps;
		int interpolStep = 0;
		int u = 0;
		while (player.isAlive())
		{
			time = player.getPosition();
			tempInterpolSteps = time / interpolStepSize;
			
			// only every 100ms the fx5 interface should change its DMX output
			if (tempInterpolSteps > interpolStep)
			{
				interpolStep = tempInterpolSteps;
				
				// Send the values to the interface
				u = 0;
				for(int i= (int) ((tempInterpolSteps)*(waveBitrate/10)); i<(tempInterpolSteps+1)*(waveBitrate/10)-1;i++)
				{
					if(i>= wavearray[0].length)
					{	for(int j = i; j<wavearray[0].length; j++)
						{
							wavearrayn[0][u] = 0;
							wavearrayn[1][u] = 0;
							u++;
						}
						break;
					}
					wavearrayn[0][u] = wavearray[0][i];
					wavearrayn[1][u] = wavearray[1][i]; 
					u++;
				}
				try
				{
					System.out.println("Zeit in sec: " + interpolStep/10.0);
					audioAna.analyze(tempInterpolSteps, wavearrayn, waveBitrate/10);
				} catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}

			// to lower cpu usage the thread should sleep a while
			// 20ms means, the signal can come 0ms to 20ms to late, but that
			// should still fit
			try
			{
				sleep(20);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}

	public void run()
	{
		this.getTime();
	}
}
